package com.example.mymvvmdemo.net.model;

import androidx.annotation.NonNull;


import com.example.mymvvmdemo.api.API;
import com.example.mymvvmdemo.constants.UrlTypeConstants;
import com.example.mymvvmdemo.retrofit.RetrofitManager;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.RequestBodyUtils;

import org.json.JSONObject;
import org.json.JSONArray;

import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * 用来请求只携带一个body的post请求
 */
public class PostBodyModel extends BaseModel {

    private IModel.PostBodyModel postBodyModel;

    public PostBodyModel(IModel.PostBodyModel postBodyModel) {
        this.postBodyModel = postBodyModel;
    }

    public void startLoadPostBody(String url, String auth_token, HashMap<String, String> hashMap, String type) {

        // 创建JSON对象来确保正确的格式
        JSONObject jsonObject = new JSONObject();
        try {
            for (String key : hashMap.keySet()) {
                if (key.equals("tag_ids")) {
                    // 将tag_ids转换为JSON数组
                    String tagIdsStr = hashMap.get(key);
                    JSONArray tagIdsArray = new JSONArray(tagIdsStr);
                    jsonObject.put(key, tagIdsArray);
                } else {
                    jsonObject.put(key, hashMap.get(key));
                }
            }
        } catch (Exception e) {
            LogUtils.e("创建JSON对象时出错: " + e.getMessage());
        }

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());

        // 只有在非登录请求时才添加 Bearer 前缀
        String formattedToken = type.equals(UrlTypeConstants.login) ? auth_token : "Bearer " + auth_token;

        RetrofitManager.getInstance().getRetrofit().create(API.class)
                .loadPostBody(url, formattedToken, body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResponseBody response) {
                        try {
                            String result = response.string();
                            //判断请求网络是否异常
                            if (isNetWorkError(result)) {
                                postBodyModel.loadPostBodyNetWorkError(result, type);
                                return;
                            }

                            JSONObject jsonObject = new JSONObject(result);
                            int code = jsonObject.getInt("code");
                            //检查是否账号异常（被挤或者token异常)
//                  boolean isError = CheckOutUtils.checkErrorCode(code);
//                  if (isError) {
//                      postBodyModel.loadPostBodyAccountError(code);
//                  } else {
                            postBodyModel.loadPostBodySuccess(result, type, code);
//                  }

                        } catch (Exception e) {
                            LogUtils.e("请求异常: " + e.getMessage());
                            postBodyModel.loadPostBodyFail(e.getMessage(), type);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        LogUtils.e("请求错误: " + e.getMessage());
                        LogUtils.e("错误类型: " + e.getClass().getName());

                        //判断请求网络是否异常
                        if (isNetWorkError(e.getMessage())) {
                            postBodyModel.loadPostBodyNetWorkError(e.getMessage(), type);
                            return;
                        }

                        if (e instanceof retrofit2.HttpException) {
                            retrofit2.HttpException httpException = (retrofit2.HttpException) e;
                            LogUtils.e("HTTP错误码: " + httpException.code());
                            try {
                                String errorBody = httpException.response().errorBody().string();
                                LogUtils.e("错误响应体: " + errorBody);
                            } catch (Exception ex) {
                                LogUtils.e("无法读取错误响应体: " + ex.getMessage());
                            }
                        }

                        postBodyModel.loadPostBodyFail(e.getMessage(), type);

                    }

                    @Override
                    public void onComplete() {
//                        LogUtils.d("请求完成");
                    }
                });
    }

    public void startLoadPostBody(String url, String auth_token, HashMap<String, String> hashMap, RequestBody body, String type) {

        // 只有在非登录请求时才添加 Bearer 前缀
        String formattedToken = type.equals(UrlTypeConstants.login) ? auth_token : "Bearer " + auth_token;

        RetrofitManager.getInstance().getRetrofit().create(API.class)
                .loadPostQueryBody(url, formattedToken, hashMap, body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResponseBody response) {
                        try {
                            String result = response.string();
                            //判断请求网络是否异常
                            if (isNetWorkError(result)) {
                                postBodyModel.loadPostBodyNetWorkError(result, type);
                                return;
                            }

                            JSONObject jsonObject = new JSONObject(result);
                            int code = jsonObject.getInt("code");
                            //检查是否账号异常（被挤或者token异常)
//                  boolean isError = CheckOutUtils.checkErrorCode(code);
//                  if (isError) {
//                      postBodyModel.loadPostBodyAccountError(code);
//                  } else {
                            postBodyModel.loadPostBodySuccess(result, type, code);
//                  }

                        } catch (Exception e) {
                            LogUtils.e("请求异常: " + e.getMessage());
                            postBodyModel.loadPostBodyFail(e.getMessage(), type);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        LogUtils.e("请求错误: " + e.getMessage());
                        LogUtils.e("错误类型: " + e.getClass().getName());

                        //判断请求网络是否异常
                        if (isNetWorkError(e.getMessage())) {
                            postBodyModel.loadPostBodyNetWorkError(e.getMessage(), type);
                            return;
                        }

                        if (e instanceof retrofit2.HttpException) {
                            retrofit2.HttpException httpException = (retrofit2.HttpException) e;
                            LogUtils.e("HTTP错误码: " + httpException.code());
                            try {
                                String errorBody = httpException.response().errorBody().string();
                                LogUtils.e("错误响应体: " + errorBody);
                            } catch (Exception ex) {
                                LogUtils.e("无法读取错误响应体: " + ex.getMessage());
                            }
                        }

                        postBodyModel.loadPostBodyFail(e.getMessage(), type);

                    }

                    @Override
                    public void onComplete() {
//                        LogUtils.d("请求完成");
                    }
                });
    }

}
